#!/bin/bash

# 重新安装 MySQL 8.0.33 并设置正确权限的脚本

echo "=== 开始重新安装 MySQL 8.0.33 ==="

# 停止并移除现有的 MySQL 容器
echo "停止并移除现有的 MySQL 容器..."
docker stop mysql 2>/dev/null || true
docker rm mysql 2>/dev/null || true

# 清理 MySQL 数据目录
echo "清理 MySQL 数据目录..."
if [ -d "./script/docker/mysql/data" ]; then
    rm -rf ./script/docker/mysql/data/*
    echo "MySQL 数据目录已清理"
else
    echo "创建 MySQL 数据目录..."
    mkdir -p ./script/docker/mysql/data
fi

# 设置最大的目录权限 (针对阿里云CentOS服务器)
echo "设置 MySQL 目录最大权限..."
mkdir -p ./script/docker/mysql/conf
mkdir -p ./script/docker/mysql/data
chmod -R 777 ./script/docker/mysql
chown -R 999:999 ./script/docker/mysql/data
chown -R 999:999 ./script/docker/mysql/conf

# 创建 MySQL 配置文件
echo "创建 MySQL 配置文件..."
cat > ./script/docker/mysql/conf/my.cnf << 'EOF'
[mysqld]
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci
default-time-zone = '+8:00'
lower_case_table_names = 1
max_connections = 2000
sql_mode = NO_ENGINE_SUBSTITUTION
# 稳定的InnoDB配置
innodb_flush_method = O_DSYNC
innodb_use_native_aio = 0
innodb_flush_log_at_trx_commit = 1
innodb_file_per_table = 1

[mysql]
default-character-set = utf8mb4

[client]
default-character-set = utf8mb4
EOF

# 启动新的 MySQL 容器
echo "启动新的 MySQL 容器..."
docker run -d \
  --name mysql \
  -p 3306:3306 \
  -e MYSQL_ROOT_PASSWORD=gzkj666 \
  -e MYSQL_DATABASE=ruoyi-tdesign \
  -e TZ=Asia/Shanghai \
  -v "$(pwd)/script/docker/mysql/data:/var/lib/mysql" \
  -v "$(pwd)/script/docker/mysql/conf:/etc/mysql/conf.d" \
  mysql:8.0.33 \
  --default-authentication-plugin=mysql_native_password \
  --character-set-server=utf8mb4 \
  --collation-server=utf8mb4_general_ci \
  --explicit_defaults_for_timestamp=true \
  --lower_case_table_names=1 \
  --innodb-flush-method=O_DSYNC \
  --innodb-use-native-aio=0 \
  --innodb-flush-log-at-trx-commit=1

echo "等待 MySQL 启动..."
sleep 30

# 检查 MySQL 是否启动成功
echo "检查 MySQL 状态..."
if docker ps | grep -q mysql; then
    echo "MySQL 容器正在运行"

    # 测试数据库连接
    echo "测试数据库连接..."
    docker exec mysql mysqladmin ping -h localhost -u root -pgzkj666 > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        echo "MySQL 数据库连接成功"
        echo "数据库地址: localhost:3306"
        echo "用户名: root"
        echo "密码: gzkj666"
        echo "数据库: ruoyi-tdesign"
    else
        echo "警告: MySQL 数据库连接测试失败"
        echo "查看日志: docker logs mysql"
    fi
else
    echo "错误: MySQL 容器未能成功启动"
    echo "查看日志: docker logs mysql"
    exit 1
fi

echo "=== MySQL 8.0.33 重新安装完成 ==="
